#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    long long countSubarrays(vector<int>& nums, int k) {
        using LL = long long;
        int mmax = 0;
        int n = nums.size(), left = 0;
        for (int i = 0; i < n; i++) if (nums[i] > mmax) mmax = nums[i];
        int count = 0;
        LL res = 0;
        for (int right = 0; right < n; right++)
        {
            int r = nums[right];
            if (r == mmax)
                ++count;
            while (count >= k)
            {
                int l = nums[left++];
                if (l == mmax)
                    --count;
            }
            res += left;
        }
        return res;
    }
};